package com.scsj.supermarket.view.activity.loginmodel;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.scsj.supermarket.R;
import com.scsj.supermarket.utils.Tool;
import com.scsj.supermarket.view.activity.baseactivitymodel.BaseActivity;

import org.json.JSONException;
import org.json.JSONObject;

import es.dmoral.toasty.Toasty;



/**
 * 第三方登录设置手机号
 * Created by love on 2017/12/7.
 */

public class ThirdLoginSetPhoneActivity extends BaseActivity implements View.OnClickListener {

    private boolean isFirst = false;
    private Intent mIntent;
    private String clentId = "";
    private String openId = "";
    private String type = "";
    private String TAG = "ThirdLoginSetPhoneActivity";
    private ImageView mBack;
    private TextView mTitle;
    private TextView mSave;
    private ImageView mShare;
    private RelativeLayout mRlActionbar;
    /**
     * 为保障您的账户安全，请绑定您未注册使用过的手机号
     */
    private TextView mHintTv;
    /**  */
    private EditText mPhoneEt;
    /**
     * 请输入验证码
     */
    private EditText mCodeTv;
    /**
     * 获取验证码
     */
    private Button mGetCodeBtn;
    /**
     * 绑定
     */
    private Button mConBtn;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_third_login_set_phone);

        initView();
    }

    @Override
    protected void createView(Bundle savedInstanceState) {

    }

    @Override
    protected void initView() {

        mTitle.setText("绑定手机号");
        isFirst = getIntent().getBooleanExtra("isFrist", false);
        if (isFirst) {
            mHintTv.setText("为保障您的账户安全，请绑定您已有商超世界账号手机号或未注册使用过的手机号");
        } else {
            mHintTv.setText("为保障您的账户安全，请绑定您未注册使用过的手机号");
        }
        RegisterCodeTimerService.setHandler(mCodeHandler);
        clentId = getIntent().getStringExtra("clentId");
        openId = getIntent().getStringExtra("openId");
        type = getIntent().getStringExtra("type");
        mIntent = new Intent(this, RegisterCodeTimerService.class);

        mBack = (ImageView) findViewById(R.id.back);
        mBack.setOnClickListener(this);
        mTitle = (TextView) findViewById(R.id.title);
        mSave = (TextView) findViewById(R.id.save);
        mShare = (ImageView) findViewById(R.id.share);
        mRlActionbar = (RelativeLayout) findViewById(R.id.rl_actionbar);
        mHintTv = (TextView) findViewById(R.id.hint_tv);
        mPhoneEt = (EditText) findViewById(R.id.phone_et);
        mCodeTv = (EditText) findViewById(R.id.codeTv);
        mGetCodeBtn = (Button) findViewById(R.id.getCodeBtn);
        mGetCodeBtn.setOnClickListener(this);
        mConBtn = (Button) findViewById(R.id.conBtn);
        mConBtn.setOnClickListener(this);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {

    }


    private void getCode() {

/*        phone	是	string	手机号
        type	是	string	1:注册;2:忘记、修改密码;3:修改手机号;4:绑定银行卡;5:修改支付密码
        userId	否	string	用户ID type=3时使用*/

        JSONObject ob = new JSONObject();

        try {
            ob.put("phone", mPhoneEt.getText().toString());
            ob.put("type", 6);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        // TODO: 2018/7/17 下边的联网方法暂时隐藏
        String data = ob.toString();
//        NetWorkUtils.postHttpRequest(Tool.getParams(data, context, Constants.mine_get_code),
//                new NetWorkUtils.HttpCallback() {
//
//                    @Override
//                    public void onSuccess(String result) {
//                        Gson gson = new Gson();
//                        startService(mIntent);
//                        MineCodeBean baseBean = gson.fromJson(result, MineCodeBean.class);
//                        if (baseBean.getRet() == MineUtils.SUCCESS_RET) {
//                            ToastUtils.showToast(context, baseBean.getMsg());
//
//                        } else {
//                            mGetCodeBtn.setEnabled(true);
//                            ToastUtils.showToast(context, baseBean.getMsg());
//                        }
//
//
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        Log.i("error", ex.toString());
//                        mGetCodeBtn.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onCancelled(Callback.CancelledException cex) {
//                        mGetCodeBtn.setEnabled(true);
//                    }
//
//                    @Override
//                    public void onFinished() {
//
//                    }
//                });
    }


    /**
     * 第三方登录
     *
     * @param openId
     * @param type
     */
    private void goLoginByThird(final String openId, final String type) {

//        if (!HttpUtil.isNetworkConnected(this)) {
//            Tool.goNoNetWork(context);
//            return;
//        }
//        dialogShow();
        JSONObject ob = new JSONObject();
        try {
            ob.put("openId", openId);
            ob.put("type", type);
            ob.put("clientId", clentId);
            ob.put("userLoginIp", "192.168.0.1");
            ob.put("phone", mPhoneEt.getText().toString());
            ob.put("code", mCodeTv.getText().toString());
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String data = ob.toString();
        // TODO: 2018/7/17 下边的联网方法暂时隐藏
//        String paramString = Tool.getParams(data, context, Constants.THREE_LOGIN_V2).toString();
//        MyLog.d(TAG, "服务器请求地址：" + paramString);
//        NetWorkUtils.postHttpRequest(Tool.getParams(data, context, Constants.THREE_LOGIN_V2),
//                new NetWorkUtils.HttpCallback() {
//                    @Override
//                    public void onSuccess(String result) {
//                        MyLog.d(TAG, "请求成功" + result);
//                        BaseBean bean = BaseBean.praseJSONObject(result);
//                        if (bean != null) {
//                            if (bean.getRet() == 1) {
////                        doPrise(bean.getData());
//                                User userBean = new Gson().fromJson(bean.getData(), User.class);
//                                if (userBean != null) {
//                                    try {
//                                        db.dropTable(UserBean.class);
//                                        db.save(userBean.getUser());
//                                        sendLoginSuccessBrodCast();
//                                        showToast(getString(R.string.login_success));
//                                        Tool.setStringShared(context, "loginType", type);
//                                        Tool.setStringShared(context, "openId", openId);
//                                        setResult(RESULT_OK);
//                                        finish();
////                                loginTim(userBean.getUser().getTimIdentifier(), userBean.getUser().getTimSignature(),0);
////                                finish();
//                                    } catch (DbException e) {
//                                        e.printStackTrace();
//                                    }
//                                }
//                            } else {
//                                showToast(bean.getMsg());
//                            }
//
//                        } else {
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable ex, boolean isOnCallback) {
//                        MyLog.e(TAG, "http请求失败：" + ex.toString());
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onCancelled(Callback.CancelledException cex) {
//                        dialogDismiss();
//                    }
//
//                    @Override
//                    public void onFinished() {
//                        dialogDismiss();
//                    }
//                });
    }


    /**
     * 倒计时Handler
     */

    @SuppressLint("HandlerLeak")
    Handler mCodeHandler = new Handler() {
        public void handleMessage(Message msg) {
            if (msg.what == RegisterCodeTimer.IN_RUNNING) {// 正在倒计时
                mGetCodeBtn.setText(msg.obj.toString());
            } else if (msg.what == RegisterCodeTimer.END_RUNNING) {// 完成倒计时
                mGetCodeBtn.setEnabled(true);
                mGetCodeBtn.setText(msg.obj.toString());
            }
        }
    };

    private void sendLoginSuccessBrodCast() {
        //开启广播
        //创建一个意图对象
        Intent intent = new Intent();
        //指定发送广播的频道
        intent.setAction("com.yitaohui.yitaogou");
        //发送广播的数据
        intent.putExtra("key", "loginSuccess");
        //发送
        sendBroadcast(intent);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.back:
                finish();
                break;
            case R.id.getCodeBtn:
                if (!TextUtils.isEmpty(mPhoneEt.getText())) {
                    if (!Tool.isPhoneNumber(mPhoneEt.getText().toString())) {
                        Toasty.info(this,"手机号码不正确").show();
                    } else {
                        mGetCodeBtn.setEnabled(false);
                        getCode();
                    }
                } else {
                    Toasty.info(this,"请输入手机号").show();

                }
                break;
            case R.id.conBtn:
                if (TextUtils.isEmpty(mPhoneEt.getText())) {
                    Toasty.info(this,"请输入手机号").show();
                } else if (!Tool.isPhoneNumber(mPhoneEt.getText().toString())) {
                    Toasty.info(this,"手机号码不正确").show();
                } else if (TextUtils.isEmpty(mCodeTv.getText())) {
                    Toasty.info(this,"请输入验证码").show();
                } else {
                    goLoginByThird(openId, type);
                }
                break;
        }
    }
}
